package com.aabte.springdocopenapi;

import com.aabte.springdocopenapi.controller.ApiException;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
public class GlobalControllerExceptionHandler {

    @ExceptionHandler(ConversionFailedException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseDTO handleConversion(ConversionFailedException ex) {
        return ResponseDTO.builder().code("400").msg("parameter error.").build();
    }

    @ExceptionHandler(ApiException.class)
    public ResponseDTO handlePersonNotFound(ApiException ex) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null != requestAttributes) {
            HttpServletResponse response = requestAttributes.getResponse();
            if (response != null) {
                response.setStatus(ex.getStatus());
                return ResponseDTO.builder().code(ex.getCode()).msg(ex.getMsg()).build();
            }
        }
        return null;
    }
}
